<template>
  <view class="charging-page">
    <!-- 顶部搜索区域 -->
    <view class="search-section">
      <u-search
        v-model="searchKeyword"
        placeholder="搜索充电桩"
        :show-action="true"
        action-text="搜索"
        @search="handleSearch"
        @custom="handleSearch"
      />
    </view>

    <!-- 筛选区域 -->
    <view class="filter-section">
      <u-tabs :list="filterTabs" @click="handleFilterChange" />
    </view>

    <!-- 充电桩列表 -->
    <view class="charging-list">
      <view 
        class="charging-item" 
        v-for="item in chargingList" 
        :key="item.id"
        @click="handleSelectCharging(item)"
      >
        <view class="charging-info">
          <view class="charging-header">
            <text class="charging-name">{{ item.pileName }}</text>
            <u-tag :text="item.workStatusName" :type="getStatusType(item.workStatus)" size="mini"></u-tag>
          </view>
          <view class="charging-details">
            <text class="charging-type">{{ item.pileTypeName }}</text>
            <text class="charging-power">功率：{{ item.powerRating }}kW</text>
            <text class="charging-price">价格：¥{{ item.unitPrice }}/kWh</text>
          </view>
          <view class="charging-location" v-if="item.lotName">
            <text class="location-text">位置：{{ item.lotName }}</text>
          </view>
          <view class="charging-status" v-if="item.workStatus === 2">
            <text class="status-text">当前功率：{{ item.currentPower }}kW</text>
            <text class="status-text">温度：{{ item.temperature }}℃</text>
          </view>
        </view>
        <view class="charging-actions">
          <u-button 
            v-if="item.workStatus === 1"
            size="mini" 
            type="primary" 
            @click.stop="handleStartCharging(item)"
          >
            开始充电
          </u-button>
          <u-button 
            v-else-if="item.workStatus === 2"
            size="mini" 
            type="warning" 
            @click.stop="handleStopCharging(item)"
          >
            停止充电
          </u-button>
          <u-button 
            size="mini" 
            type="info" 
            @click.stop="handleViewDetail(item)"
          >
            详情
          </u-button>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <u-loadmore 
      :status="loadmoreStatus"
      @loadmore="loadMore"
    />

    <!-- 充电中弹窗 -->
    <u-popup v-model="chargingVisible" mode="bottom" border-radius="16">
      <view class="charging-popup">
        <view class="popup-header">
          <text class="popup-title">充电中</text>
          <u-icon name="close" @click="chargingVisible = false"></u-icon>
        </view>
        
        <view class="charging-status">
          <view class="status-item">
            <text class="status-label">充电桩</text>
            <text class="status-value">{{ currentCharging.pileName }}</text>
          </view>
          <view class="status-item">
            <text class="status-label">开始时间</text>
            <text class="status-value">{{ currentCharging.startTime }}</text>
          </view>
          <view class="status-item">
            <text class="status-label">充电时长</text>
            <text class="status-value">{{ currentCharging.duration }}</text>
          </view>
          <view class="status-item">
            <text class="status-label">已充电量</text>
            <text class="status-value">{{ currentCharging.chargedAmount }}kWh</text>
          </view>
          <view class="status-item">
            <text class="status-label">当前费用</text>
            <text class="status-value">¥{{ currentCharging.currentFee }}</text>
          </view>
          <view class="status-item">
            <text class="status-label">当前功率</text>
            <text class="status-value">{{ currentCharging.currentPower }}kW</text>
          </view>
        </view>
        
        <view class="charging-actions">
          <u-button type="warning" @click="handleStopCharging">停止充电</u-button>
          <u-button type="primary" @click="handleViewRecord">查看记录</u-button>
        </view>
      </view>
    </u-popup>

    <!-- 开始充电弹窗 -->
    <u-popup v-model="startChargingVisible" mode="bottom" border-radius="16">
      <view class="start-charging-popup">
        <view class="popup-header">
          <text class="popup-title">开始充电</text>
          <u-icon name="close" @click="startChargingVisible = false"></u-icon>
        </view>
        
        <view class="charging-form">
          <view class="form-item">
            <text class="form-label">选择车辆</text>
            <u-picker 
              :show="showVehiclePicker"
              :range="vehicleOptions"
              range-key="label"
              @change="onVehicleChange"
              @cancel="showVehiclePicker = false"
            />
            <u-input 
              v-model="chargingForm.vehicleId"
              placeholder="请选择车辆"
              readonly
              @click="showVehiclePicker = true"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">目标充电量 (kWh)</text>
            <u-input 
              v-model="chargingForm.targetAmount"
              type="number"
              placeholder="请输入目标充电量"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">预计费用</text>
            <text class="estimated-fee">¥{{ estimatedFee }}</text>
          </view>
        </view>
        
        <view class="charging-actions">
          <u-button @click="startChargingVisible = false">取消</u-button>
          <u-button type="primary" @click="confirmStartCharging" :loading="submitLoading">确认充电</u-button>
        </view>
      </view>
    </u-popup>

    <!-- 充电记录弹窗 -->
    <u-popup v-model="recordVisible" mode="bottom" border-radius="16">
      <view class="record-popup">
        <view class="popup-header">
          <text class="popup-title">充电记录</text>
          <u-icon name="close" @click="recordVisible = false"></u-icon>
        </view>
        
        <view class="record-list">
          <view 
            class="record-item" 
            v-for="record in chargingRecords" 
            :key="record.id"
          >
            <view class="record-header">
              <text class="record-time">{{ record.startTime }}</text>
              <u-tag :text="record.chargingStatusName" :type="getRecordStatusType(record.chargingStatus)" size="mini"></u-tag>
            </view>
            <view class="record-details">
              <text class="record-pile">充电桩：{{ record.pileName }}</text>
              <text class="record-amount">充电量：{{ record.chargeAmount }}kWh</text>
              <text class="record-fee">费用：¥{{ record.totalFee }}</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 费用详情弹窗 -->
    <u-popup v-model="feeVisible" mode="bottom" border-radius="16">
      <view class="fee-popup">
        <view class="popup-header">
          <text class="popup-title">费用详情</text>
          <u-icon name="close" @click="feeVisible = false"></u-icon>
        </view>
        
        <view class="fee-details">
          <view class="fee-item">
            <text class="fee-label">充电量</text>
            <text class="fee-value">{{ feeDetails.chargeAmount }}kWh</text>
          </view>
          <view class="fee-item">
            <text class="fee-label">电费单价</text>
            <text class="fee-value">¥{{ feeDetails.unitPrice }}/kWh</text>
          </view>
          <view class="fee-item">
            <text class="fee-label">电费</text>
            <text class="fee-value">¥{{ feeDetails.electricityFee }}</text>
          </view>
          <view class="fee-item">
            <text class="fee-label">服务费</text>
            <text class="fee-value">¥{{ feeDetails.serviceFee }}</text>
          </view>
          <view class="fee-item fee-total">
            <text class="fee-label">总计</text>
            <text class="fee-value">¥{{ feeDetails.totalFee }}</text>
          </view>
        </view>
        
        <view class="fee-actions">
          <u-button type="primary" @click="handlePayment">立即支付</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onShow, computed } from 'vue'
import { chargingPileAPI } from '@/api/parking'

// 作者：Wu.Liang

// 响应式数据
const searchKeyword = ref('')
const chargingList = ref([])
const chargingVisible = ref(false)
const startChargingVisible = ref(false)
const recordVisible = ref(false)
const feeVisible = ref(false)
const loadmoreStatus = ref('more')
const submitLoading = ref(false)

// Picker显示状态
const showVehiclePicker = ref(false)

// 筛选标签
const filterTabs = ref([
  { name: '全部' },
  { name: '空闲' },
  { name: '充电中' },
  { name: '故障' }
])

// 当前充电信息
const currentCharging = ref({})

// 充电表单
const chargingForm = reactive({
  pileId: null,
  vehicleId: '',
  targetAmount: ''
})

// 车辆选项
const vehicleOptions = ref([
  { label: '京A12345', value: 1 },
  { label: '京B67890', value: 2 }
])

// 充电记录
const chargingRecords = ref([])

// 费用详情
const feeDetails = ref({
  chargeAmount: 0,
  unitPrice: 0,
  electricityFee: 0,
  serviceFee: 0,
  totalFee: 0
})

// 计算预计费用
const estimatedFee = computed(() => {
  if (!chargingForm.targetAmount || !currentCharging.value.unitPrice) {
    return '0.00'
  }
  return (parseFloat(chargingForm.targetAmount) * parseFloat(currentCharging.value.unitPrice)).toFixed(2)
})

// 生命周期
onMounted(() => {
  loadChargingData()
})

onShow(() => {
  loadChargingData()
})

// 方法定义
const loadChargingData = async () => {
  try {
    const response = await chargingPileAPI.getList({
      keyword: searchKeyword.value
    })
    chargingList.value = response.data.records || []
  } catch (error) {
    console.error('加载充电桩数据失败:', error)
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    })
  }
}

const handleSearch = async () => {
  await loadChargingData()
}

const handleFilterChange = (index) => {
  const statusMap = ['', 1, 2, 3]
  const status = statusMap[index]
  loadChargingData({ workStatus: status })
}

const handleSelectCharging = (item) => {
  // 查看充电桩详情
  uni.navigateTo({
    url: `/pages/parking/charging-detail?id=${item.id}`
  })
}

const handleStartCharging = (item) => {
  currentCharging.value = item
  chargingForm.pileId = item.id
  startChargingVisible.value = true
}

const handleStopCharging = async (item) => {
  try {
    await uni.showModal({
      title: '确认停止',
      content: '确定要停止充电吗？'
    })
    
    const response = await chargingPileAPI.stopCharging({
      pileId: item.id
    })
    
    uni.showToast({
      title: '停止充电成功',
      icon: 'success'
    })
    
    chargingVisible.value = false
    loadChargingData()
  } catch (error) {
    console.error('停止充电失败:', error)
    uni.showToast({
      title: '停止充电失败',
      icon: 'none'
    })
  }
}

const handleViewDetail = (item) => {
  uni.navigateTo({
    url: `/pages/parking/charging-detail?id=${item.id}`
  })
}

const onVehicleChange = (value) => {
  chargingForm.vehicleId = value
  showVehiclePicker.value = false
}

const confirmStartCharging = async () => {
  if (!chargingForm.vehicleId) {
    uni.showToast({
      title: '请选择车辆',
      icon: 'none'
    })
    return
  }
  
  if (!chargingForm.targetAmount) {
    uni.showToast({
      title: '请输入目标充电量',
      icon: 'none'
    })
    return
  }
  
  submitLoading.value = true
  try {
    const response = await chargingPileAPI.startCharging({
      pileId: chargingForm.pileId,
      vehicleId: chargingForm.vehicleId,
      targetAmount: parseFloat(chargingForm.targetAmount)
    })
    
    uni.showToast({
      title: '开始充电成功',
      icon: 'success'
    })
    
    startChargingVisible.value = false
    currentCharging.value = response.data
    chargingVisible.value = true
    
    // 重置表单
    Object.assign(chargingForm, {
      pileId: null,
      vehicleId: '',
      targetAmount: ''
    })
  } catch (error) {
    console.error('开始充电失败:', error)
    uni.showToast({
      title: '开始充电失败',
      icon: 'none'
    })
  } finally {
    submitLoading.value = false
  }
}

const handleViewRecord = () => {
  uni.navigateTo({
    url: '/pages/parking/charging-record'
  })
}

const loadMore = async () => {
  loadmoreStatus.value = 'loading'
  try {
    // 加载更多数据
    loadmoreStatus.value = 'more'
  } catch (error) {
    loadmoreStatus.value = 'noMore'
  }
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'error',   // 离线
    1: 'success', // 空闲
    2: 'warning', // 充电中
    3: 'error'    // 故障
  }
  return typeMap[status] || 'info'
}

const getRecordStatusType = (status) => {
  switch (status) {
    case 1: return 'warning'
    case 2: return 'success'
    default: return 'info'
  }
}

const handlePayment = () => {
  uni.navigateTo({
    url: `/pages/payment/index?amount=${feeDetails.value.totalFee}&type=charging`
  })
}
</script>

<style scoped>
.charging-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

.search-section {
  background-color: #fff;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.filter-section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.charging-list {
  background-color: #fff;
}

.charging-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #eee;
}

.charging-item:last-child {
  border-bottom: none;
}

.charging-info {
  flex: 1;
  margin-right: 20rpx;
}

.charging-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.charging-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.charging-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  margin-bottom: 10rpx;
}

.charging-type,
.charging-power,
.charging-price {
  font-size: 26rpx;
  color: #666;
}

.charging-location {
  margin-bottom: 10rpx;
}

.location-text {
  font-size: 24rpx;
  color: #999;
}

.charging-actions {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.charging-popup,
.start-charging-popup {
  background-color: #fff;
  border-radius: 32rpx 32rpx 0 0;
  padding: 40rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.charging-status {
  margin-bottom: 40rpx;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  font-size: 28rpx;
  color: #666;
}

.status-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.charging-form {
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}

.estimated-fee {
  font-size: 32rpx;
  color: #f56c6c;
  font-weight: bold;
}

.charging-actions {
  display: flex;
  gap: 20rpx;
}

.record-list {
  padding: 30rpx;
  max-height: 600rpx;
  overflow-y: auto;
}

.record-item {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.record-time {
  font-size: 28rpx;
  color: #333;
}

.record-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.record-pile,
.record-amount,
.record-fee {
  font-size: 26rpx;
  color: #666;
}

.fee-details {
  padding: 30rpx;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.fee-total {
  border-top: 1rpx solid #eee;
  padding-top: 20rpx;
  margin-top: 20rpx;
}

.fee-label {
  font-size: 28rpx;
  color: #666;
}

.fee-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.fee-actions {
  padding: 30rpx;
}
</style> 